package com.scs.application.modules.wm.utils;

import com.scs.application.core.exception.BusinessException;
import com.scs.application.core.utils.StringUtils;
import com.scs.application.modules.cfg.utils.ParameterUtils;
import com.scs.application.modules.wm.enums.UniqueCodeType;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 */
public class UniqueCodeUtils {

    /**
     * 依据条码/唯一编码区分条码类型
     *
     * @param uniqueCode
     * @return
     */
    public static UniqueCodeType getUniqueCodeType(String uniqueCode) {

        if (StringUtils.isBlank(uniqueCode)) {
            throw new BusinessException("未知的条码类型:%s",uniqueCode);
        }
        String upperCase = uniqueCode;
        if (upperCase.startsWith("SN") || upperCase.startsWith("JP")) {
            return UniqueCodeType.SN;
        }
        if (isRFID(uniqueCode)) {
            return UniqueCodeType.RFID;
        }
        if (upperCase.startsWith("UDI")) {
            return UniqueCodeType.UDI;
        }
        throw new BusinessException("未知的条码类型:%s",uniqueCode);
    }

    /***
     * 判断是否是rfid
     * @param uniqueCode
     * @return
     */
    public static boolean isRFID(String uniqueCode) {
        Pattern pattern = Pattern.compile(ParameterUtils.getRFIDRegex());
        Matcher matcher = pattern.matcher(uniqueCode);
        return matcher.matches();
    }

    /**
     * 截取rfid字符串
     * @param uniqueCode
     * @return
     */
    public static String getRFID(String uniqueCode) {
        String regex = ParameterUtils.getRFIDRegex();
        regex = regex.replaceAll("\\$", "");
        Pattern pattern = Pattern.compile(regex);
        Matcher matcher = pattern.matcher(uniqueCode);
        if (matcher.find()) {
            return matcher.group(0);
        }
        return "";
    }
}
